
// 已开启命名空间
import { login, getUserInfo, getUserInfoById } from '@/api/user.js'
import {
  setToken,
  getToken,
  removeToken,
  setTokenTime
} from '@/utils/auth.js'
const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
// 设置token
  setToken(state, payload) {
    state.token = payload
    setToken(payload)
  },

  // 给userInfo赋值
  setUserInfo(state, payload) {
    state.userInfo = payload
  },

  // 退出登录
  logout(state) {
    state.token = null
    state.userInfo = {}
    removeToken()
  }
}
const actions = {
  // 登录
  async login(context, payload) {
    const res = await login(payload)

    // 在登录时获取当前的时间 用于后面判断token有没有过期
    setTokenTime()
    context.commit('setToken', res)
  },

  // 获取用户首页信息
  async  getUserInfo(context) {
    const res = await getUserInfo()
    const userInfo = await getUserInfoById(res.userId)
    context.commit('setUserInfo', { ...res, ...userInfo })
  }

}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

